<template>
	<swiper class="home-swiper" :current="activeIndex" @change="change">
		<swiper-item v-for="(item, index) in tab" :key="index" :class="swiper-item">
			<listItem
				:list="listCatchData[index]"
				@loadmore="loadmore"
				:load="load[index]"
			></listItem>
		</swiper-item>
	</swiper>
</template>

<script>
	import listScroll from '../list-scroll/list-scroll.vue'
	import listCard from '../list-card/list-card.vue'
	import listItem from './list-item.vue'
	export default {
		components: {
			listScroll,
			listCard,
			listItem
		},
		props: {
			tab: {
				type: Array,
				default () {
					return []
				}
			},
			activeIndex: {
				type: Number,
				default: 0
			}
		},
		watch: {
			tab(newVal) {
				if (newVal.length === 0) return
				this.listCatchData = {}
				this.load = {}
				this.getList(this.activeIndex)
			}
		},
		data() {
			return {
				list: [],
				listCatchData: {},
				load: {},
				pageSize: 4
			};
		},
		created() {
			this.getList(0)
		},
		methods: {
			change(e) {
				const { current } = e.detail
				this.$emit('change', e.detail.current)
				// 当数据不存在或者数据长度为 0 的时候，请求数据
				if (!this.listCatchData[current] || this.listCatchData[current].length === 0) {
					console.log('数据加载了~~~~')
					this.getList(current)
				}
			},
			getList(current) {
				if (!this.load[current]) {
					this.load[current] = {
						page: 1,
						loading: 'loading'
					}
				}
				this.$api.get_list({
					name: this.tab[current].name,
					page: this.load[current].page,
					pageSize: this.pageSize
				}).then((res) => {
					console.log(res)
					const { data } = res
					if (data.length === 0) {
						let oldLoad = {}
						oldLoad.loading = 'noMore'
						oldLoad.page = this.load[current].page
						console.log(this.load)
						this.$set(this.load, current, oldLoad)
						// 强制渲染页面
						this.$forceUpdate()
						return
					}
					console.log('请求数据', data)
					// 更好的显示数据
					let oldList = this.listCatchData[current] || []
					oldList.push(...data)
					this.$set(this.listCatchData, current, oldList)
				})
			},
			loadmore() {
				if (this.load[this.activeIndex].loading === 'noMore') return
				this.load[this.activeIndex].page++
				this.getList(this.activeIndex)
			}
		}
	}
</script>

<style lang="scss">
.home-swiper {
	height: 100%;
	.swiper-item {
		height: 100%;
		overflow: hidden;
	}
}
</style>
